package net.qiqb.core.domain;

import cn.hutool.core.util.TypeUtil;
import net.qiqb.core.domain.annotation.EntityIdGenerator;

import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.HashMap;
import java.util.Map;

public class EntityIdGeneratorRegistrar {

    private final Map<Class<?>, EntityIdGenerator<?>> MAP = new HashMap<>();

    public <ID> EntityIdGenerator<ID> get(Class<ID> idClazz) {
        EntityIdGenerator<?> generator = MAP.get(idClazz);
        if (generator == null) {
            generator = new SnowflakeIdGenerator<>(idClazz);
            MAP.put(idClazz, generator);
        }
        return (EntityIdGenerator<ID>) generator;
    }

    public boolean register(EntityIdGenerator<?> entityIdGenerator) {
        final String className = entityIdGenerator.getClass().getName();
        if (className.contains("Lambda")) {
            throw new RuntimeException("暂不支持lambda表达式写法");
        }
        final Map<Type, Type> typeMap = TypeUtil.getTypeMap(entityIdGenerator.getClass());
        for (Map.Entry<Type, Type> entry : typeMap.entrySet()) {
            final Type key = entry.getKey();
            if (key instanceof TypeVariable<?> typeVariable) {
                final GenericDeclaration genericDeclaration = typeVariable.getGenericDeclaration();
                if (genericDeclaration.equals(EntityIdGenerator.class)) {
                    final Type value = entry.getValue();
                    if (value instanceof Class<?> valueClass) {
                        this.MAP.put(valueClass, entityIdGenerator);
                        return true;
                    }
                }
            }
        }
        return false;
    }


}
